package hxg.tcptest.demo4;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;

/**
 * @author HeXiangGuang
 * @create 2021-06-30 21:38
 * 实现注册功能
 */
public class RegitsThread extends Thread{
    @Override
    public void run() {
        try {
            //1创建ServerSocket
            ServerSocket listener = new ServerSocket(6666);
            //调用accept方法
            System.out.println("服务器已经启动------");
            Socket socket = listener.accept();
            //获取输入输出流
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"));
            //4接收客户端发送的数据{id : 1001，name :tom，pwd :123，age : 20 }
            String json = br.readLine();
            //subString()方法去除{}，第一个{,为参数1,第二个}为json.length()-1
            //上面处理后的数据为id : 1001，name :tom，pwd :123，age : 20 然后在用split分割符分割数据用数组接收
            String[] infos = json.substring(1, json.length() - 1).split(",");
            //然后取id的值value
            String[] split = infos[0].split(":");
            String id = split[1];
            //5加载属性文件
            Properties properties = Tools.loadProperties();
            //6判断
            if (properties.containsKey(id)){
                //有
                bw.write("此用户已经存在---");
            }else {
                //保存属性文件
                Tools.saveProperties(json);
                bw.write("注册成功！");
            }
            bw.newLine();
            bw.flush();
            bw.close();
            br.close();
            socket.close();
            listener.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
